package com.sgb.capital.view.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sgb.capital.R;
import com.sgb.capital.callback.MyZTextWatcher;
import com.sgb.capital.databinding.FinanceflowFragmentBinding;
import com.sgb.capital.model.Bean;
import com.sgb.capital.model.PayFlowBean;
import com.sgb.capital.model.RecordsBean;
import com.sgb.capital.utils.AdapterOnItemClick;
import com.sgb.capital.utils.Utils;
import com.sgb.capital.view.pop.SelectPop;
import com.sgb.capital.view.pop.ZSelectPop;
import com.sgb.capital.view.ui.activity.CauseDetailActivity;
import com.sgb.capital.view.ui.activity.FinanceFlowDetailsActivity;
import com.sgb.capital.view.ui.activity.WithdrawalDetailActivity;
import com.sgb.capital.view.ui.adapter.FinanceFlowAdapter;
import com.sgb.capital.view.ui.adapter.FinanceFlowItemAdapter;
import com.sgb.capital.view.widget.xrecyclerview.ZXRecyclerView;
import com.sgb.capital.viewmodel.FinanceFlowModel;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

/**
 * 作者:张磊
 * 日期:2021/4/16 0016
 * 说明:账户流水
 */
public class FinanceFlowFragment extends AppLazyFragment {
    FinanceFlowModel mModel;
    private FinanceflowFragmentBinding mBinding;
    private FinanceFlowAdapter mAdapter;
    private SelectPop mSelectPop;
    private List<Bean> mTimeBeans;
    private FinanceFlowItemAdapter mFlowItemAdapter;

    private List<Bean> mTradeFlowTypeBeans;
    private TextView mTextView;
    private ImageView mImg;
    private PayFlowBean mBean;
    private ZSelectPop mZSelectPop;
    private String mTime;
    private List<Bean> mPayType;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.financeflow_fragment, container, false);
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        // TODO: 2021/4/20 0020 选项
        mBinding.rvItem.setLayoutManager(new GridLayoutManager(Utils.getContext(), 3));
        mFlowItemAdapter = new FinanceFlowItemAdapter(null);
        mBinding.rvItem.setAdapter(mFlowItemAdapter);
        // TODO: 2021/4/20 0020 列表
        mAdapter = new FinanceFlowAdapter(getActivity(), null);
        mBinding.rvList.setLayoutManager(new GridLayoutManager(Utils.getContext(), 1));
        mBinding.rvList.setAdapter(mAdapter);
        // TODO: 2021/4/21 0021 弹框及数据
        mSelectPop = new SelectPop(getActivity());
        mZSelectPop = new ZSelectPop(getActivity());
        mSelectPop.setBgView(mBinding.grayLayout);
        mZSelectPop.setBgView(mBinding.grayLayout);
        mModel = new ViewModelProvider(this).get(FinanceFlowModel.class);
    }


    @Override
    public void initObserve() {
        mModel.mSelBean.observe(this, bean -> {
            mZSelectPop.setData(bean);
            mZSelectPop.showPopwindow(mBinding.view, 0, 0);
        });
        mModel.mPayFlowBeanMutableLiveData.observe(this, recordsBeans -> list(recordsBeans));
    }

    public void initListener() {
        mZSelectPop.setOnDismissListener(() -> {
            mImg.setRotation(0);
            if (mZSelectPop.mIsClick) {
                String name = mZSelectPop.mName1.name != null ? mZSelectPop.mName2.name == null ? mZSelectPop.mName1.name : mZSelectPop.mName2.name : "交易类型";
                mTextView.setText(name.length() > 5 ? name.substring(0, 5) + "..." : name);
                mTextView.setTextColor(Utils.getColor(!name.contains("交易类型") ? R.color.color_EF4033 : R.color.color_333333));
                mImg.setImageResource(!name.contains("交易类型") ? R.mipmap.down : R.mipmap.ic_down_arrow_n);
                // 状态(1.待审核 2.已驳回 3.待寄出 4.已寄出 5.已撤销 6.未开票 7.已开票 )
                mBean.page = 1;
                mBean.sourceType = name.contains("订单退款") ? "4" : name.contains("交易类型") ? null : name.contains("订单交易") ? "1" : name.contains("转账汇款") ? "2" : name.contains("账户提现") ? "3" : "1";
                if (mBean.sourceType != null && mBean.sourceType.contains("1")) {
                    mBean.tradeType = name.contains("订单交易") ? null : name;
                    mBean.sourceType = "1";
                } else {
                    mBean.tradeType = null;
                }
                mBean.searchValue = mBinding.etSs.getText().toString().trim();
                mModel.list(this, mBean);
            }
            if (mTextView.getText().toString().contains("发票状态")) {
                mTextView.setTextColor(Utils.getColor(R.color.color_666666));
            }
        });

        mBinding.etSs.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                mBean.page = 1;
                mBean.searchValue = mBinding.etSs.getText().toString().trim();
                mModel.list(FinanceFlowFragment.this, mBean);
            }
            return false;
        });
        mBinding.etSs.addTextChangedListener(new MyZTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String editable = mBinding.etSs.getText().toString();
                String str = Utils.stringFilter(mBinding.etSs.getText().toString());
                if (!editable.equals(str)) {
                    mBinding.etSs.setText(str);
                    mBinding.etSs.setSelection(str.length());
                }
            }
        });

        mAdapter.setOnItemClick(new AdapterOnItemClick<RecordsBean>() {
            @Override
            public void onItemClick(RecordsBean recordsBean, int position) {
                if (recordsBean.sourceType.contains("3")) {
                    WithdrawalDetailActivity.start(getActivity(), recordsBean.flowNo);
                } else if (recordsBean.sourceType.contains("4")) {
                    CauseDetailActivity.start(getActivity(), new Gson().toJson(recordsBean),recordsBean.flowNo);
                } else {
                    FinanceFlowDetailsActivity.start(getActivity(), new Gson().toJson(recordsBean), "");
                }
            }
        });
        mBinding.rvList.setLoadingListener(new ZXRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mBean.page = 1;
                mBean.searchValue = mBinding.etSs.getText().toString().trim();
                mModel.list(FinanceFlowFragment.this, mBean);
            }

            @Override
            public void onLoadMore() {
                mBean.page++;
                mBean.searchValue = mBinding.etSs.getText().toString().trim();
                mModel.list(FinanceFlowFragment.this, mBean);
            }
        });
        mSelectPop.setOnDismissListener(() -> {
            if (mSelectPop.mType == 1 && mSelectPop.mPos1 == 0) {
                mTextView.setText("交易类型");
                mBean.tradeType = null;
            } else if (mSelectPop.mType == 2 && mSelectPop.mPos2 == 0) {
                mTextView.setText("入账时间");
                mTime = null;
                mBean.startTime = null;
                mBean.endTime = null;
            } else if (mSelectPop.mType == 3 && mSelectPop.mPos3 == 0) {
                mTextView.setText("收支类型");
                mBean.tradeFlowType = 0;
            } else if (mSelectPop.mType == 4 && mSelectPop.mPos4 == 0) {
                mTextView.setText("支付方式");
                mBean.payType = 0;
            } else {
                if (mSelectPop.mIsClick) {
                    mTextView.setText(mSelectPop.mBean.name.length() > 5 ? mSelectPop.mBean.name.substring(0, 5) + "..." : mSelectPop.mBean.name);
                    if (mSelectPop.mType == 1) {
                        mBean.tradeType = mSelectPop.mBean.name;
                    } else if (mSelectPop.mType == 3) {
                        mBean.tradeFlowType = mSelectPop.mPos3;
                    } else if (mSelectPop.mType == 2) {
                        if (mSelectPop.mPos2 == 0) {
                            mTime = null;
                            mBean.startTime = null;
                            mBean.endTime = null;
                        } else {
                            mTime = mSelectPop.mBean.name.contains("今日") ? Utils.getStartAndEndTime(0, 0, "今日")
                                    : mSelectPop.mBean.name.contains("最近一周") ? Utils.getStartAndEndTime(1, 7, "最近一周")
                                    : mSelectPop.mBean.name.contains("最近一个月") ? Utils.getStartAndEndTime(2, 1, "最近一个月")
                                    : mSelectPop.mBean.name.contains("最近三个月") ? Utils.getStartAndEndTime(2, 3, "最近三个月")
                                    : mSelectPop.mBean.name.contains("最近六个月") ? Utils.getStartAndEndTime(2, 6, "最近六个月")
                                    : mSelectPop.mBean.name.contains("最近一年") ? Utils.getStartAndEndTime(3, 1, "最近一年")
                                    : Utils.getStartAndEndTime(3, 3, "最近三年");
                            mBean.startTime = mTime.split("-")[0];
                            mBean.endTime = mTime.split("-")[1];
                        }
                    }
                }
            }
            mImg.setRotation(0);
            if (mSelectPop.mIsClick) {
                mTextView.setTextColor(Utils.getColor(mSelectPop.mType == 1 ?
                        mSelectPop.mPos1 != 0 ? R.color.color_EF4033 : R.color.color_333333 :
                        mSelectPop.mType == 2 ? mSelectPop.mPos2 != 0 ? R.color.color_EF4033 : R.color.color_333333 :
                        mSelectPop.mType == 3 ? mSelectPop.mPos3 != 0 ? R.color.color_EF4033 : R.color.color_333333 :
                                mSelectPop.mPos4 != 0 ? R.color.color_EF4033 : R.color.color_333333
                ));
                mImg.setImageResource(mSelectPop.mType == 1 ? mSelectPop.mPos1 != 0 ?
                        R.mipmap.down : R.mipmap.ic_down_arrow_n :
                        mSelectPop.mType == 2 ? mSelectPop.mPos2 != 0 ? R.mipmap.down : R.mipmap.ic_down_arrow_n :
                        mSelectPop.mType == 3 ? mSelectPop.mPos3 != 0 ? R.mipmap.down : R.mipmap.ic_down_arrow_n :
                        mSelectPop.mPos4 != 0 ? R.mipmap.down : R.mipmap.ic_down_arrow_n
                );
                mBean.page = 1;
                mBean.searchValue = mBinding.etSs.getText().toString().trim();
                mModel.list(FinanceFlowFragment.this, mBean);
            }
            mSelectPop.mIsClick = false;
        });
        mFlowItemAdapter.setOnItemClickListener((adapter, view, position) -> {
            LinearLayout linearLayout = (LinearLayout) view;
            mTextView = (TextView) linearLayout.getChildAt(0);
            mImg = (ImageView) linearLayout.getChildAt(1);
            mImg.setRotation(180);
            switch (position) {
                case 0:
                    if (mZSelectPop.mDatas.size() == 0) {
                        mModel.getTradeType(mActivity);
                        return;
                    }
                    break;
                case 1:
                    mSelectPop.mType = 2;
                    mSelectPop.setData(mTimeBeans);
                    mSelectPop.mAdapter.setDefItem(mSelectPop.mPos2);
                    break;
                case 2:
                    mSelectPop.mType = 3;
                    mSelectPop.setData(mTradeFlowTypeBeans);
                    mSelectPop.mAdapter.setDefItem(mSelectPop.mPos3);
                    break;
                case 3:
                    mSelectPop.mType = 4;
                    mSelectPop.setData(mPayType);
                    mSelectPop.mAdapter.setDefItem(mSelectPop.mPos4);
                    break;
            }

            if (position == 1 || position == 2) {
                mSelectPop.showPopwindow(mBinding.view, 0, 0);
            } else {
                mZSelectPop.showPopwindow(mBinding.view, 0, 0);
            }
        });
    }

    @Override
    protected void onLazyLoad() {
        mTradeFlowTypeBeans = new ArrayList<>();
        Utils.setBeans(mTradeFlowTypeBeans, new String[]{"全部", "收入", "支出"});
        mTimeBeans = new ArrayList<>();
        Utils.setBeans(mTimeBeans, new String[]{"全部", "今日", "最近一周", "最近一个月", "最近三个月", "最近六个月", "最近一年", "最近三年"});
        mPayType = Utils.setDatas(new String[]{"全部", "余额支付", "B2B网银", "快捷支付", "微信扫码支付", "支付宝扫码支付"});
        mBean = new PayFlowBean();
        List<Bean> beans = new ArrayList<>();
        beans.add(new Bean("交易类型"));
        beans.add(new Bean("入账时间"));
        beans.add(new Bean("收支类型"));
        beans.add(new Bean("支付方式"));
        mFlowItemAdapter.setNewInstance(beans);
        mModel.list(this, mBean);
    }


    /**
     * 财务流水
     *
     * @param data
     */
    public void list(List<RecordsBean> data) {
        mBinding.rvList.refreshComplete();
        if (data == null) {
            return;
        }
        if (mBean.page == 1) {
            mBinding.errorView.setVisibility(data.size() != 0 ? View.GONE : View.VISIBLE);
            mBinding.rvList.setLoadingMoreEnabled(true);
            mBinding.rvList.refreshComplete();
            mAdapter.setDatas(data);
        } else {
            if (data.size() != 0) {
                mBinding.rvList.loadMoreComplete();
                mAdapter.addDatas(data);
            } else {
                mBinding.rvList.setNoMore(true);
            }
        }
        mAdapter.notifyDataSetChanged();
    }
}